<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>退款审核</title>
  <script src="/js/vue.js"></script>
  <link type="text/css" rel="stylesheet" href="/css/index.css">
  <script src="/js/index.js"></script>
  <script src="/js/axios.min.js"></script>
</head>
<body>
<div id="app">
  <!-- 退款审核卡片 -->
  <el-card shadow="hover" style="margin: 10px;">
    <div slot="header">
      <span>退款审核</span>
    </div>

    <!-- 搜索区域 -->
    <el-row :gutter="10" style="margin-bottom: 10px;">
      <el-col :span="4">
        <el-input size="mini" v-model="searchForm.orderNo" placeholder="订单号"></el-input>
      </el-col>
      <el-col :span="4">
        <el-input size="mini" v-model="searchForm.scenicName" placeholder="景区名称"></el-input>
      </el-col>
      <el-col :span="4">
        <el-date-picker size="mini" v-model="searchForm.createTime" type="date" placeholder="下单时间"></el-date-picker>
      </el-col>
      <el-col :span="4">
        <el-select size="mini" v-model="searchForm.orderState" placeholder="订单状态" clearable>
          <el-option label="待审核" value="14"></el-option>
          <el-option label="已审核(退款成功)" value="24"></el-option>
          <el-option label="已审核(退款失败)" value="23"></el-option>
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-button size="mini" icon="el-icon-search" type="primary" @click="search">搜索</el-button>
        <el-button size="mini" type="default" @click="loadOrderData" icon="el-icon-refresh">刷新</el-button>
      </el-col>
    </el-row>

    <!-- 待审核订单表格 -->
    <el-table :data="tableData" border stripe style="width: 100%" empty-text="暂无订单数据">
      <el-table-column prop="orderNo" label="订单号" min-width="100"></el-table-column>
      <el-table-column prop="scenicName" label="景区名称" min-width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.scenicName">{{ scope.row.scenicName }}</span>
          <span v-else-if="scope.row.orderItemList && scope.row.orderItemList.length > 0">
            <span v-if="scope.row.orderItemList[0].ticket && scope.row.orderItemList[0].ticket.scenic && scope.row.orderItemList[0].ticket.scenic.scenicName">
              {{ scope.row.orderItemList[0].ticket.scenic.scenicName }}
            </span>
            <span v-else-if="scope.row.orderItemList[0].ticket && scope.row.orderItemList[0].ticket.scenicName">
              {{ scope.row.orderItemList[0].ticket.scenicName }}
            </span>
            <span v-else-if="scope.row.orderItemList[0].scenic && scope.row.orderItemList[0].scenic.scenicName">
              {{ scope.row.orderItemList[0].scenic.scenicName }}
            </span>
            <span v-else>未知景区</span>
          </span>
          <span v-else>未知景区</span>
        </template>
      </el-table-column>
      <el-table-column prop="orderTprice" label="订单金额(元)" width="100">
        <template slot-scope="scope">{{ scope.row.orderTprice ? scope.row.orderTprice.toFixed(2) : '0.00' }}</template>
      </el-table-column>
      <el-table-column prop="orderCount" label="数量" width="80"></el-table-column>
      <el-table-column prop="orderTime" label="下单时间" width="150"></el-table-column>
      <el-table-column prop="orderQpname" label="取票人" width="100"></el-table-column>
      <el-table-column prop="orderQprsj" label="联系电话" width="140"></el-table-column>
      <el-table-column label="订单状态" width="120">
        <template slot-scope="scope">
          <el-tag :type="getOrderStateTagType(scope.row.orderState)">
            {{ getOrderStateText(scope.row.orderState) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="viewOrderDetail(scope.row)">查看详情</el-button>
          <el-button 
            v-if="scope.row.orderState === '14'" 
            size="mini" 
            type="success" 
            @click="approveRefund(scope.row)">同意</el-button>
          <el-button 
            v-if="scope.row.orderState === '14'" 
            size="mini" 
            type="danger" 
            @click="rejectRefund(scope.row)">拒绝</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            style="margin-top: 10px; text-align: right;">
    </el-pagination>
  </el-card>

  <!-- 订单详情弹窗 -->
  <el-dialog title="订单详情" :visible.sync="detailDialogVisible" width="60%">
    <el-form :model="detailForm" label-width="120px" class="detail-form">
      <el-row>
        <el-col :span="12">
          <el-form-item label="订单号：">
            <span>{{ detailForm.orderNo }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="订单状态：">
            <el-tag :type="getOrderStateTagType(detailForm.orderState)">
              {{ getOrderStateText(detailForm.orderState) }}
            </el-tag>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="订单金额：">
            <span>￥{{ detailForm.orderTprice ? detailForm.orderTprice.toFixed(2) : '0.00' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="门票数量：">
            <span>{{ detailForm.orderCount }} 张</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="下单时间：">
            <span>{{ detailForm.orderTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="游玩日期：">
            <span>{{ detailForm.orderYwrq }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="取票人：">
            <span>{{ detailForm.orderQpname }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话：">
            <span>{{ detailForm.orderQprsj }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="订单项：">
        <el-table :data="detailForm.orderItemList" border stripe style="width: 100%">
          <el-table-column label="景区名称" width="180">
            <template slot-scope="scope">
              <span v-if="scope.row.ticket && scope.row.ticket.scenic && scope.row.ticket.scenic.scenicName">
                {{scope.row.ticket.scenic.scenicName }}
              </span>
              <span v-else-if="scope.row.ticket && scope.row.ticket.scenicName">
                {{scope.row.ticket.scenicName }}
              </span>
              <span v-else-if="scope.row.scenic && scope.row.scenic.scenicName">
                {{scope.row.scenic.scenicName }}
              </span>
              <span v-else>
                {{scope.row.scenicName || '未知景区' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="ticket.ticketName" label="门票名称" width="180">
            <template slot-scope="scope">
              <span v-if="scope.row.ticket">
                {{scope.row.ticket.ticketName }}
              </span>
              <span v-else>
                {{scope.row.ticketName || '未知门票' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="unitPrice" label="单价(元)" width="100">
            <template slot-scope="scope">{{ scope.row.unitPrice ? scope.row.unitPrice.toFixed(2) : '0.00' }}</template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="80"></el-table-column>
          <el-table-column label="小计(元)" width="100">
            <template slot-scope="scope">{{ (scope.row.unitPrice * scope.row.quantity).toFixed(2) }}</template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item label="退款信息：" v-if="refundInfo && detailForm.orderState === '14'">
        <el-card>
          <el-row>
            <el-col :span="12">
              <el-form-item label="退款金额：">￥{{ refundInfo.refundIje ? refundInfo.refundIje.toFixed(2) : '0.00' }}</el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请时间：">{{ refundInfo.refundTime }}</el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="退款原因：">{{ refundInfo.refundFullmsg }}</el-form-item>
        </el-card>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="detailDialogVisible = false">关闭</el-button>
    </div>
  </el-dialog>

  <!-- 审核操作对话框 -->
  <el-dialog :title="auditDialogTitle" :visible.sync="auditDialogVisible" width="40%">
    <el-form :model="auditForm" label-width="100px" :rules="auditRules" ref="auditForm">
      <el-form-item :label="auditType === 'approve' ? '同意说明：' : '拒绝原因：'" prop="reason">
        <el-input
          type="textarea"
          v-model="auditForm.reason"
          placeholder="请输入操作说明"
          :rows="4">
        </el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="auditDialogVisible = false">取消</el-button>
      <el-button
        type="primary"
        @click="submitAudit"
        :loading="auditLoading">
        确定
      </el-button>
    </div>
  </el-dialog>
</div>

<script>
  // 日期格式化工具函数
  function formatDate(date) {
    if (!date) return '';
    const d = new Date(date);
    let month = '' + (d.getMonth() + 1);
    let day = '' + d.getDate();
    let hour = '' + d.getHours();
    let minute = '' + d.getMinutes();
    let second = '' + d.getSeconds();

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;
    if (hour.length < 2) hour = '0' + hour;
    if (minute.length < 2) minute = '0' + minute;
    if (second.length < 2) second = '0' + second;

    return `${d.getFullYear()}-${month}-${day} ${hour}:${minute}:${second}`;
  }

  new Vue({
    el: '#app',
    data() {
      return {
        // 表格数据相关
        tableData: [],
        currentPage: 1,
        pageSize: 10,
        total: 0,
        // 搜索表单
        searchForm: {
          orderNo: '',
          scenicName: '',
          createTime: ''
        },
        // 详情弹窗相关
        detailDialogVisible: false,
        detailForm: {},
        refundInfo: null,
        // 审核弹窗相关
        auditDialogVisible: false,
        auditLoading: false,
        auditType: '', // 'approve' 或 'reject'
        auditDialogTitle: '',
        auditForm: {
          reason: ''
        },
        auditRules: {
          reason: [
            { required: true, message: '请输入操作说明', trigger: 'blur' }
          ]
        },
        currentOrder: null
      }
    },
    created() {
      // 页面加载时默认加载第一页数据
      this.loadOrderData();
    },
    methods: {
      // 加载待审核订单数据
      loadOrderData() {
        // 构建搜索参数（处理日期格式）
        const searchParams = {
          ...this.searchForm,
          createTime: this.searchForm.createTime ? formatDate(this.searchForm.createTime) : ''
          // 移除了固定的 orderState: '14'，现在通过搜索表单控制
        };

        // 如果没有选择订单状态，默认查询待审核状态的订单
        if (!searchParams.orderState) {
          searchParams.orderState = '14';
        }

        // 调用分页查询接口
        axios.post('/order/queryByPage', {
          pageNo: this.currentPage,
          pageSize: this.pageSize,
          data: searchParams
        })
        .then(res => {
          if (res.data.code === 200) {
            this.tableData = res.data.data.list || [];
            this.total = res.data.data.total || 0;
          } else {
            this.$message.error('加载订单数据失败：' + (res.data.message || '接口返回异常'));
          }
        })
        .catch(err => {
          console.error('加载订单数据异常：', err);
          this.$message.error('网络错误或接口不可用');
        });
      },

      // 分页大小变更
      handleSizeChange(val) {
        this.pageSize = val;
        this.loadOrderData();
      },

      // 当前页码变更
      handleCurrentChange(val) {
        this.currentPage = val;
        this.loadOrderData();
      },

      // 搜索按钮点击事件
      search() {
        this.currentPage = 1; // 重置为第一页
        this.loadOrderData();
      },

      // 重置搜索表单
      resetSearch() {
        this.searchForm = {
          orderNo: '',
          scenicName: '',
          createTime: '',
          orderState: '' // 添加订单状态重置
        };
        this.currentPage = 1;
        this.loadOrderData();
      },

      // 查看订单详情
      viewOrderDetail(row) {
        axios.get(`/order/queryById?orderId=${row.orderId}`)
          .then(response => {
            if (response.data.code === 200) {
              this.detailForm = response.data.data;
              // 加载退款信息
              this.loadRefundInfo(this.detailForm.orderNo);
              this.detailDialogVisible = true;
            } else {
              this.$message.error('获取订单详情失败：' + (response.data.message || '未知错误'));
            }
          })
          .catch(error => {
            this.$message.error('网络错误：' + error.message);
          });
      },

      // 加载退款信息
      loadRefundInfo(orderNo) {
        if (!orderNo) return;

        axios.post('/refund/queryByPage', {
          pageNo: 1,
          pageSize: 1,
          data: { orderNo: orderNo }
        })
        .then(res => {
          if (res.data.code === 200) {
            const refundList = res.data.data.list;
            if (refundList && refundList.length > 0) {
              this.refundInfo = refundList[0];
            } else {
              this.refundInfo = null;
            }
          } else {
            this.$message.warning('查询退款记录失败：' + res.data.message);
          }
        })
        .catch(error => {
          this.$message.error('查询退款记录出错：' + error.message);
        });
      },

      // 同意退款
      approveRefund(order) {
        this.currentOrder = order;
        this.auditType = 'approve';
        this.auditDialogTitle = '同意退款';
        this.auditForm.reason = '同意退款申请';
        this.auditDialogVisible = true;
      },

      // 拒绝退款
      rejectRefund(order) {
        this.currentOrder = order;
        this.auditType = 'reject';
        this.auditDialogTitle = '拒绝退款';
        this.auditForm.reason = '拒绝退款申请';
        this.auditDialogVisible = true;
      },

      // 提交审核结果
      submitAudit() {
        this.$refs.auditForm.validate((valid) => {
          if (valid) {
            this.auditLoading = true;

            // 根据审核类型执行不同操作
            if (this.auditType === 'approve') {
              // 同意退款 - 更新订单状态为"已退款"(24)
              this.processRefundApproval();
            } else if (this.auditType === 'reject') {
              // 拒绝退款 - 更新订单状态为"退款审核不通过结束"(23)
              this.processRefundRejection();
            }
          }
        });
      },

      // 处理退款同意
      processRefundApproval() {
        console.log('开始处理退款同意流程，订单号:', this.currentOrder.orderNo);
        
        // 先查询退款记录
        console.log('正在查询退款记录...');
        axios.post('/refund/queryByPage', {
          pageNo: 1,
          pageSize: 10,
          data: { orderNo: this.currentOrder.orderNo }
        })
        .then(res => {
          console.log('查询退款记录响应:', res);
          if (res.data.code === 200) {
            const refundList = res.data.data.list;
            console.log('查询到的退款记录列表:', refundList);
            if (refundList && refundList.length > 0) {
              const sortedRefunds = refundList.sort((a, b) =>
                      new Date(b.refundTime) - new Date(a.refundTime)
              );
              const refund = sortedRefunds[0];
              console.log('选择最新的退款记录:', refund);

              // 先更新订单状态
              console.log('准备更新订单状态为已退款(24)');
              return axios.post('/order/updateStateByNo', null, {
                params: {
                  orderNo: this.currentOrder.orderNo,
                  orderState: '24' // 已退款
                }
              })
              .then(response => {
                console.log('更新订单状态响应:', response);
                if (response && response.data && response.data.code === 200) {
                  console.log('订单状态更新成功，准备更新退款记录');
                  // 订单状态更新成功后，再更新退款记录
                  return this.updateRefundRecord('1', this.auditForm.reason, refund);
                } else {
                  const errorMsg = (response && response.data && response.data.message) ? 
                    response.data.message : '未知错误';
                  console.error('更新订单状态失败：' + errorMsg);
                  throw new Error('更新订单状态失败：' + errorMsg);
                }
              });
            } else {
              console.error('未找到退款记录');
              throw new Error('未找到退款记录');
            }
          } else {
            const errorMsg = (res && res.data && res.data.message) ? res.data.message : '未知错误';
            console.error('查询退款记录失败：' + errorMsg);
            throw new Error('查询退款记录失败：' + errorMsg);
          }
        })
        .catch(error => {
          console.error('退款同意流程错误:', error);
          this.$message.error('操作失败: ' + (error.message || '未知错误'));
          this.auditLoading = false;
        });
      },

      // 处理退款拒绝
      processRefundRejection() {
        this.auditLoading = true;
        console.log('开始处理退款拒绝流程，订单号:', this.currentOrder.orderNo);

        // 1. 先查询退款记录
        console.log('正在查询退款记录...');
        axios.post('/refund/queryByPage', {
          pageNo: 1,
          pageSize: 10,
          data: { orderNo: this.currentOrder.orderNo }
        })
                .then(res => {
                  console.log('查询退款记录响应:', res);
                  if (res.data.code === 200) {
                    const refundList = res.data.data.list;
                    console.log('查询到的退款记录列表:', refundList);
                    if (refundList && refundList.length > 0) {
                      const sortedRefunds = refundList.sort((a, b) =>
                              new Date(b.refundTime) - new Date(a.refundTime)
                      );
                      const refund = sortedRefunds[0];
                      console.log('选择最新的退款记录:', refund);

                      // 2. 先更新退款记录
                      // 传递完整的退款记录数据，避免数据库约束违规
                      const updateData = {
                        refundId: refund.refundId,
                        orderNo: refund.orderNo,
                        refundSerialno: refund.refundSerialno,
                        refundIje: refund.refundIje,
                        refundTime: refund.refundTime,
                        refundRespcode: 'REFUND_FAILED',
                        refundResult: '2',
                        refundFullmsg: this.auditForm.reason || '退款审核不通过'
                      };
                      
                      console.log('准备更新退款记录，更新数据:', updateData);
                      return axios.put('/refund/update', updateData);
                    } else {
                      console.error('未找到退款记录');
                      throw new Error('未找到退款记录');
                    }
                  } else {
                    const errorMsg = (res && res.data && res.data.message) ? res.data.message : '未知错误';
                    console.error('查询退款记录失败: ' + errorMsg);
                    throw new Error('查询退款记录失败: ' + errorMsg);
                  }
                })
                .then(updateRes => {
                  console.log('更新退款记录响应:', updateRes);
                  if (updateRes && updateRes.data && updateRes.data.code === 200) {
                    console.log('退款记录更新成功，准备更新订单状态');
                    // 3. 退款记录更新成功后，再更新订单状态
                    return axios.post('/order/updateStateByNo', null, {
                      params: {
                        orderNo: this.currentOrder.orderNo,
                        orderState: '23'
                      }
                    });
                  } else {
                    const errorMsg = (updateRes && updateRes.data && updateRes.data.message) ? 
                      updateRes.data.message : '未知错误';
                    console.error('更新退款记录失败: ' + errorMsg);
                    throw new Error('更新退款记录失败: ' + errorMsg);
                  }
                })
                .then(orderRes => {
                  console.log('更新订单状态响应:', orderRes);
                  if (orderRes && orderRes.data && orderRes.data.code === 200) {
                    console.log('订单状态更新成功');
                    this.$message.success('已拒绝退款');
                    this.auditDialogVisible = false;
                    this.auditLoading = false;
                    this.loadOrderData();
                  } else {
                    const errorMsg = (orderRes && orderRes.data && orderRes.data.message) ? 
                      orderRes.data.message : '未知错误';
                    console.error('更新订单状态失败: ' + errorMsg);
                    throw new Error('更新订单状态失败: ' + errorMsg);
                  }
                })
                .catch(error => {
                  console.error('退款拒绝流程错误:', error);
                  this.$message.error('操作失败: ' + (error.message || '未知错误'));
                  this.auditLoading = false;
                });
      },

      // 更新退款记录
      updateRefundRecord(result, reason, refund) {
        console.log('开始更新退款记录，参数:', {result, reason, refund});
        
        // 构建完整的更新数据，包含所有原始字段
        const updateData = {
          refundId: refund.refundId,
          orderNo: refund.orderNo, // 保留原始值
          refundSerialno: refund.refundSerialno, // 保留原始值
          refundIje: refund.refundIje, // 保留原始值
          refundTime: refund.refundTime, // 保留原始值
          refundRespcode: result === '1' ? 'REFUND_SUCCESS' : 'REFUND_FAILED',
          refundResult: result,
          refundFullmsg: reason || (result === '1' ? '退款审核通过' : '退款审核不通过')
        };

        console.log('完整的更新数据:', updateData);

        return axios.put('/refund/update', updateData)
                .then(updateRes => {
                  console.log('更新退款记录响应:', updateRes);
                  if (updateRes && updateRes.data && updateRes.data.code === 200) {
                    console.log('退款记录更新成功');
                    this.$message.success(result === '1' ? '已同意退款' : '已拒绝退款');
                    this.auditDialogVisible = false;
                    this.auditLoading = false;
                    this.loadOrderData();
                  } else {
                    const errorMsg = (updateRes && updateRes.data && updateRes.data.message) ? 
                      updateRes.data.message : '未知错误';
                    console.error('更新退款记录失败：' + errorMsg);
                    throw new Error('更新退款记录失败：' + errorMsg);
                  }
                })
                .catch(error => {
                  console.error('更新退款记录网络错误：', error);
                  throw new Error('更新退款记录网络错误：' + (error.message || '未知错误'));
                });
      },

      // 获取订单状态标签类型
      getOrderStateTagType(state) {
        const tagMap = {
          '11': 'warning',   // 待付款
          '12': 'success',   // 已付款/预订成功
          '13': 'info',      // 已取票
          '14': 'primary',   // 待审核
          '15': 'danger',    // 待退款
          '20': 'info',      // 待付款退单结束
          '21': 'danger',    // 付款超时结束
          '22': 'danger',    // 预订成功退单结束
          '23': 'danger',    // 退款审核不通过结束
          '24': 'success',   // 退款完成结束
          '25': 'info',      // 取票超时结束
          '26': 'info',      // 退票结束
          '27': 'info',      // 点评超时结束
          '28': 'success'    // 点评完成结束
        };
        return tagMap[state] || 'info';
      },

      // 获取订单状态文本
      getOrderStateText(state) {
        const textMap = {
          '11': '待付款',
          '12': '已付款',
          '13': '已取票',
          '14': '待审核',
          '15': '待退款',
          '20': '待付款退单结束',
          '21': '付款超时结束',
          '22': '预订成功退单结束',
          '23': '退款审核不通过结束',
          '24': '退款完成结束',
          '25': '取票超时结束',
          '26': '退票结束',
          '27': '点评超时结束',
          '28': '点评完成结束'
        };
        return textMap[state] || '未知状态';
      }
    }
  })
</script>

<style>
  /* 详情表单样式优化 */
  .detail-form .el-form-item {
    margin-bottom: 16px;
  }
</style>
</body>
</html>